package com.eclub.emotion.rootstone.serializer.io;


/**
 * 
 * @author Edison
 * 
 */
public class Serializer {

	private Serializer() {

	}

	static class SerializerHolder {
		static Serializer instance = new Serializer();
	}

	public static Serializer getInstance() {
		return SerializerHolder.instance;
	}

	/**
	 * 
	 * @param o
	 *            object instance that serialized.
	 * @return
	 * @throws Exception
	 */
	public byte[] serialize(Object o) throws Exception {
		RsOutput out = new RsOutput();
		try {
			if (o == null) {
				SerializerFactory.getSerializer(null).writeObject(o, out);
			} else {
				SerializerFactory.getSerializer(o.getClass()).writeObject(o, out);
			}
			return out.toByteArray();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	public Object deserialize(byte[] bArray, Class clazz) throws Exception{
		RsInput stream = null;
		try {
			stream = new RsInput(bArray);
			return SerializerFactory.getSerializer(clazz).readObject(stream, clazz);
		} finally {
			if (stream != null) {
				stream.close();
			}
		}
	}

}
